﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchoolWeb.Models;
using System.Web.Security;

namespace GameSchoolWeb.Controllers
{
	[Authorize]
	public class ExamController : Controller
	{
		ICourseRepository m_repository;

		public ExamController()
		{
			m_repository = new CourseRepository();
		}

		public ExamController(ICourseRepository rep)
		{
			m_repository = rep;
		}

		public ActionResult Index()
		{
			return View();
		}

		/*
		 *	Details skilar upplýsingum um próf fyrir kennara
		 */
		[HttpGet]
		public ActionResult Details(int? id)
		{
			if (id == null) return View("NotFound");
			var examItem = (from e in m_repository.Exams()
							where e.id == id
							select e).SingleOrDefault();

			var questionItems = from q in m_repository.Questions()
								where q.examId == id
								select q;

			ExamIndexModelView vm = new ExamIndexModelView(examItem, questionItems);

			return View(vm);
		}

		[HttpGet]
		public ActionResult GetExams(int? id)
		{
			if (id == null) return View("NotFound");

			// model eru próf í núverandi borði
			var model = from e in m_repository.Exams()
						where e.levelId == id.Value
						orderby e.dDateAdded descending
						select e;

			var lvlId = id.Value;

			ExamListModelView vm = new ExamListModelView(model, lvlId);

			return View(vm);
		}

		[HttpGet]
		public ActionResult CreateExam()
		{
			return View(new Exam());
		}

		[HttpPost]
		public ActionResult CreateExam(FormCollection formdata, int? id)
		{
			Exam examItem = new Exam();
			UpdateModel(examItem);

			if (examItem != null)
			{
				examItem.levelId = id.Value;
				examItem.dDateAdded = DateTime.Now;
				m_repository.AddExam(examItem);
				m_repository.Save();

				return RedirectToAction("GetExams", new { id = id.Value });
			}

			return View("NotFound");
		}

		/*
		 * TurnInExam nær í próf fyrir nemanda
		 */
		[HttpGet]
		public ActionResult TurnInExam(int? id)
		{
			if (id == null) return View("NotFound");
			var examItem = (from e in m_repository.Exams()
							where e.id == id.Value
							select e).SingleOrDefault();

			var questionItems = from q in m_repository.Questions()
								where q.examId == id.Value
								select q;

			var turnInExamItems = (from t in m_repository.TurnInExam()
								   where t.examId == id.Value
								   select t).SingleOrDefault();

			ExamIndexModelView vm = new ExamIndexModelView(examItem, questionItems, turnInExamItems);

			return View(vm);
		}

		[HttpPost]
		public ActionResult TurnInExam(FormCollection formdata, int? id)
		{
			if (id == null) return View("NotFound");
			decimal countCorrectAns = 0;
			decimal numberQuestions = 0;

			Exam examItem = new Exam();
			Question questionItem = new Question();
			TurnInExam turnInExamItem = new TurnInExam();
			UserRegistration userRegistrationItem = new UserRegistration();
			ExamIndexModelView vm = new ExamIndexModelView();
			ExamTurninQuestion examTurnInQuestionItem = new ExamTurninQuestion();

			UpdateModel(vm);

			if (id.HasValue)
			{
				// exam er prófið sem tekið er.
				var exam = (from ex in m_repository.Exams()
							where ex.id == id.Value
							select ex).SingleOrDefault();

				if (exam != null)
				{
					// ef prófið er til eru sóttar spurningar og titill prófs
					var questions = from q in m_repository.Questions()
									where q.examId == id.Value
									select q;

					var nPoints = (from p in m_repository.Exams()
								   where p.id == id.Value
								   select p.nPoints).SingleOrDefault();

					var title = (from t in m_repository.Exams()
								 where t.id == id.Value
								 select t.strTitle).SingleOrDefault();

					// UserGuid er auðkenni núverandi notanda
					Guid UserGuid = (Guid)Membership.GetUser().ProviderUserKey;

					foreach (var question in questions)
					{
						/*spurningar sóttar úr prófi og settar inn í skilatöflu fyrir 
						nemandann sem tók prófið*/
						examTurnInQuestionItem.strOption1 = question.striOptionOne;
						examTurnInQuestionItem.strOption2 = question.strOptionTwo;
						examTurnInQuestionItem.strOption3 = question.strOptionThree;
						examTurnInQuestionItem.strOption4 = question.strOptionFour;
						examTurnInQuestionItem.strOption5 = question.strOptionFive;
						examTurnInQuestionItem.questionId = question.id;
						examTurnInQuestionItem.UserId = UserGuid;
						numberQuestions++;

						/* strengur sem tekinn var úr  radio buttons breytt yfir í
						 heiltölu */
						var selected = formdata[question.id.ToString()];
						examTurnInQuestionItem.nSelected = Convert.ToInt32(selected);

						m_repository.AddExamTurninQuestion(examTurnInQuestionItem);

						if (selected == question.nCorrectOption.ToString())
						{
							// spurningu var svarað rétt 
							countCorrectAns++;
						}
					}

					m_repository.Save();
					if (numberQuestions == 0) return View("NoQuestions");
					turnInExamItem.nScore = ((nPoints / numberQuestions) * countCorrectAns);					/*Þetta er ekki í vinnslu*/

					int x = (int)turnInExamItem.nScore;
					turnInExamItem.nScore = x;
					turnInExamItem.dReturnDate = DateTime.Now;
					turnInExamItem.strTitle = title;
					turnInExamItem.examId = id.Value;
					turnInExamItem.UserId = UserGuid;

					userRegistrationItem.nStudentPoints = userRegistrationItem.nStudentPoints + x;			//Henda skori inn í UserRegistration töfluna

					m_repository.AddTurnInExam(turnInExamItem);
					m_repository.Save();

					// Hér er búið að fara í gegnum allar spurningar og er búið að skrifa niðurstöðuna í grunninn.
				}
			}

			return RedirectToAction("ExamTurnedIn", new { id = id.Value });
		}

		/*
		 * Nær í niðurstöðu prófs sem notandi hefur lokið.
		 */
		[HttpGet]
		public ActionResult ExamTurnedIn(int? id)
		{
			if (id == null) return View("NotFound");
			var examItem = (from e in m_repository.Exams()
							where e.id == id
							select e).SingleOrDefault();

			var questionItems = from q in m_repository.Questions()
								where q.examId == id
								select q;

			// turnInExamItem hefur að geyma upplýsingar um niðurstöðu prófs
			var turnInExamItem = (from t in m_repository.TurnInExam()
								  where t.examId == id.Value
								  select t).SingleOrDefault();

			var title = (from t in m_repository.Exams()
						 where t.id == id.Value
						 select t.strTitle).SingleOrDefault();

			ExamIndexModelView vm = new ExamIndexModelView(examItem, questionItems, turnInExamItem);

			return View(vm);
		}

		[HttpGet]
		public ActionResult AddQuestions()
		{
			return View(new Question());
		}

		[HttpPost]
		public ActionResult AddQuestions(FormCollection formdata, int? id)
		{
			if (id == null) return View("NotFound");
			Question questionItem = new Question();
			UpdateModel(questionItem);

			if (questionItem != null)
			{
				questionItem.examId = id.Value;
				m_repository.AddQuestions(questionItem);
				m_repository.Save();

				return RedirectToAction("GetExams", new { id = questionItem.Exam.levelId });
			}
			return View("NotFound");
		}


		[HttpGet]
		public ActionResult AddTurnInExam()
		{
			return View(new TurnInExam());
		}

		/*
		 * AddTurnInExam skilar inn í gagnagrunn 
		 * niðurstöðum úr prófi sem nemandi tekur
		 **/
		[HttpPost]
		public ActionResult AddTurnInExam(FormCollection formdata, int? id)
		{
			if (id == null) return View("NotFound");
			TurnInExam turnInExamItem = new TurnInExam();
			UpdateModel(turnInExamItem);
			turnInExamItem.examId = id.Value;

			if (turnInExamItem != null)
			{
				m_repository.AddTurnInExam(turnInExamItem);
				m_repository.Save();

				return View();
			}

			return View("NotFound");
		}

	}
}
